
//
// utorrent web request
//
#import "UtorrentWebRequest.h"

@implementation UtorrentWebRequest

//
// result
//
@synthesize result															= _result;

//
// decode json
//
@synthesize decodeJson														= _decodeJson;

//
// guid
//
@synthesize guidCookie														= _guidCookie;

//
// init
//
- (id)initWithDecodeJson:(BOOL)decodeJson
{
	//
	// call super
	//
	self																	= [super init];
	if(!self)
		return nil;
	
	self.decodeJson															= decodeJson;
	
	return self;
}

//
// dealloc
//
- (void)dealloc
{
	self.result																= nil;
	
	[super dealloc];
}

//
// setup request
//
- (void)setupRequest
{
	//
	// call super
	//
	[super setupRequest];
	
	//
	// setup cookie
	//
	if(self.guidCookie.length)
	{
		NSDate* expires														= [NSDate dateWithTimeIntervalSinceNow:0x7fffffff];
		NSHTTPCookie* sessionIdCookie										= [self cookieWithName:@"GUID" value:self.guidCookie expires:expires];
		NSMutableArray* cookies												= [NSMutableArray arrayWithObject:sessionIdCookie];
		[self.request setAllHTTPHeaderFields:[NSHTTPCookie requestHeaderFieldsWithCookies:cookies]];
	}
}

//
// finished
//
- (void)connectionDidFinishLoading:(NSURLConnection*)connection
{
	NSArray* cookies														= [NSHTTPCookie cookiesWithResponseHeaderFields:[self.response allHeaderFields] forURL:[self.request URL]];
	for(NSHTTPCookie* cookie in cookies)
	{
		if([cookie.name isEqualToString:@"GUID"])
			self.guidCookie													= cookie.value;
	}
	
	if(self.response.statusCode == 200)
	{
		if(self.decodeJson)
		{
			//
			// decode result
			//
			NSError* error													= nil;
			self.result														= [NSJSONSerialization JSONObjectWithData:self.dataBuffer options:kNilOptions error:&error];
			self.error														= error;
		}
	}
	
	[super connectionDidFinishLoading:connection];
}

@end
